package com.studio49.exmple.common.util;

import java.util.Random;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.studio49.exmple.common.constant.SysConstant;


public class PubAppUtils {

	private static final Logger logger = LogManager.getLogger(PubAppUtils.class);

	/**
	 * token 密匙
	 */
	private final static String TOKEN_KEY = "yingxin-youjiao-token-key-v-1";

	/**
	 * 生成token标识(MD5加密)
	 * 
	 * @param user
	 * @return
	 */
	public static synchronized String getTokenKey(String key) {
		try {
			// 根据token密匙及机器码生成token标识
//			int index = (int) (Math.random()*100);
			String tokenInfo = TOKEN_KEY + "&A&" + key;
			String md5 = MD5Utils.md5ByUtf8(tokenInfo);
//			String aesEncryptUtf8 = CryptoUtils.aesEncryptUtf8(tokenInfo);
			return SysConstant.TOKEN_BEGIN + md5;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("app登录用户生成token标识失败!", e);
			return null;
		}
	}

	/**
	 * 获取验证码唯一标识
	 * 
	 * @param phoneNumber
	 * @param deviceCode
	 * @return
	 */
	public static String getVerificationCodeKey(String moduleFlag, String mobile) {
//		if (SysConstant.REGISTER_VERIFICATION_CODE_FLAG.equals(moduleFlag)) {
//			return REGISTER_VERIFICATION_CODE_KEY + "&A&" + mobile;
//		}
//		if (SysConstant.DIFFERENT_DEVICE_VERIFICATION_CODE_FLAG.equals(moduleFlag)) {
//			return DIFFERENT_DEVICE_VERIFICATION_CODE_KEY + "&A&" + mobile;
//		}
//		if (SysConstant.RESET_PWD_VERIFICATION_CODE_FLAG.equals(moduleFlag)) {
//			return RESET_PWD_VERIFICATION_CODE_KEY + "&A&" + mobile;
//		}
		return moduleFlag + "&" + mobile;
	}

	/**
	 * 获取随机数
	 * 
	 * @param digCount
	 * @return
	 */
	public static String getRandomNumber(int digCount) {
		Random random = new Random();
		StringBuilder sb = new StringBuilder(digCount);
		for (int i = 0; i < digCount; i++) {
			sb.append((char) ('0' + random.nextInt(10)));
		}
		return sb.toString();
	}

	/**
	 * long加密成16进制字符串
	 * @param userId
	 * @return
	 */
	public static String encodeToHexStr(Long userId) {
		long mod = userId % 2;
		long val = 0;
		//偶数
		if (mod == 0) {
			val = (userId + 30) * 8;
		} else {
			val = (userId + 30) * 9;
		}
		//转16进制
		String hexString = Long.toHexString(val);
		return hexString;
	}
	
	public static Long decodeHexStr(String hexStr) {
		Long val = Long.parseLong(hexStr, 16);
		long mod = val % 2;
		//偶数
		if (mod == 0) {
			val = val / 8 - 30;
		} else {
			val = val / 9 - 30;
		}
		return val;
	}
	
	
	public static void main(String[] args) {
//		System.out.println(getRandomNumber(5));
		String hexStr = encodeToHexStr((long)13);
		System.out.println(hexStr);
		Long val = decodeHexStr("165d");
		System.out.println(val);
	}
}
